package com.ds.infra.rpc.example.consumer.service;

import com.ds.infra.rpc.example.api.OrderService;
import com.ds.infra.rpc.example.api.dto.OrderDTO;
import com.ds.infra.rpc.example.api.dto.OrderItemDTO;
import com.ds.infra.rpc.example.api.exception.ApiException;
import com.ds.infra.rpc.example.api.exception.ErrorCode;
import com.ds.infra.rpc.example.consumer.client.ProductClient;
import com.ds.infra.rpc.example.consumer.dao.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductClient productClient;

    @Override
    public OrderDTO createOrder(OrderDTO orderDTO) throws ApiException {
        System.out.println("====创建订单：orderDTO = " + orderDTO);
        // 验证商品库存
        for (OrderItemDTO item : orderDTO.getItems()) {
            System.out.println("==productId===" + item.getProductId() + "===数量==" + item.getQuantity());
            boolean success = productClient.reduceStock(item.getProductId(), item.getQuantity());
            if (!success) {
                throw new ApiException(ErrorCode.PRODUCT_STOCK_INSUFFICIENT);
            }
        }
        // 计算总金额
        BigDecimal totalAmount = orderDTO.getItems().stream()
                .map(item -> item.getProductPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 设置订单信息
        orderDTO.setOrderNo(UUID.randomUUID().toString());
        orderDTO.setTotalAmount(totalAmount);
        orderDTO.setStatus(0); // 0-已创建
        orderDTO.setCreateTime(new Date());

        // 保存订单
        return orderRepository.save(orderDTO);
    }

    @Override
    public OrderDTO getOrderById(Long orderId) throws ApiException {
        return orderRepository.findById(orderId)
                .orElseThrow(() -> new ApiException(ErrorCode.ORDER_NOT_FOUND));
    }

    @Override
    public boolean cancelOrder(Long orderId) throws ApiException {
        OrderDTO order = getOrderById(orderId);
        if (order.getStatus() != 0) {
            throw new ApiException(ErrorCode.ORDER_CANCEL_FAILED.getCode(), "只有未支付的订单可以取消");
        }
        order.setStatus(4); // 4-已取消
        orderRepository.save(order);
        return true;
    }

    @Override
    public List<OrderDTO> getOrdersByUserId(Long userId) throws ApiException {
        return orderRepository.findByUserId(userId);
    }
}
